<template>
	<page-meta :page-style="'overflow:' + (isShowPopup ? 'hidden' : 'visible')"></page-meta>
	<view class="page-container bg-grey" v-if="scenicData">
		<up-navbar
			safeAreaInsetTop
			fixed
			:bgColor="navbarcfg.bgColor"
			@left-click="pageBack"
			:title="navbarcfg.title"
		></up-navbar>

		<zjy-sticky-tab
			:tabs="tabs"
			:scrollTop="scrollTopVal"
			:flex="true"
			v-model="isReached"
			ref="onTabRef"
		></zjy-sticky-tab>
		<!-- 轮播 -->
		<detail-banner :listData="scenicData.detail_urls"></detail-banner>

		<!-- 预定产品 -->
		<view id="order-product" class="order-product">
			<!-- 景区信息 -->
			<detail-info
				:scenicData="scenicData"
				@handleShowNotice="handleShowNotice"
				@handleShowPhone="handleShowPhone"
			></detail-info>
			<!-- 票务信息 -->
			<view id="ticket-business" class="ticket-business">
				<!-- 可选日期 -->
				<view
					class="optional-date"
					:style="{
						top: `calc(${statusBarHeight + navbarHeight}px + 86rpx)`,
					}"
				>
					<!-- 今日选项 -->
					<view class="date" :class="{ selected: isSelected('today') }" @click="selectDateType('today')">
						<text>订今日</text>
						<image class="icon-filter" v-if="isSelected('today')" :src="imgBaseUrl + 'filter-icon.png'" />
					</view>

					<!-- 明日选项 -->
					<view
						class="date"
						:class="{ selected: isSelected('tomorrow') }"
						@click="selectDateType('tomorrow')"
					>
						<text>订明日</text>
						<image
							class="icon-filter"
							v-if="isSelected('tomorrow')"
							:src="imgBaseUrl + 'filter-icon.png'"
						/>
					</view>

					<!-- 指定日期选项 -->
					<view class="date" :class="{ selected: isSelected('custom') }" @click="openDateCalendar">
						<text>
							{{ isSelected("custom") ? dayjs(selectedDate).format("MM月DD日") : "指定日期" }}
						</text>
						<image
							:src="imgBaseUrl + 'icon-right.png'"
							class="icon-16 ml-8 mt-2"
							v-if="!isSelected('custom')"
						/>
						<image class="icon-filter" v-if="isSelected('custom')" :src="imgBaseUrl + 'filter-icon.png'" />
					</view>
				</view>

				<template v-if="productList.length > 0">
					<view class="ticket">
						<!-- 左侧分类 -->
						<view
							class="ticket-category"
							:style="{
								top: `calc(${statusBarHeight + navbarHeight}px + 88rpx + 108rpx)`,
							}"
						>
							<view
								v-for="(item, index) in businessTypes"
								:key="index"
								class="category"
								:class="{ active: currentIndex === index }"
								@click="handleCategoryClick(index)"
							>
								{{ item }}
							</view>
						</view>
						<!-- 右侧内容 -->
						<view class="ticket-list">
							<view
								v-for="(item, index) in productList"
								:key="index"
								class="ticket-item"
								:id="`ticket-${index}`"
							>
								<view class="title">{{ item.business_type_name }}</view>
								<!-- ticket内容 -->
								<detail-tour-tickets
									@handleBooking="handleBooking"
									@changeBookingTipsShow="changeBookingTipsShow"
									v-for="(ticketItem, index) in item.items"
									:key="index"
									:data="ticketItem"
									v-if="
										[ScenicBusinessTypes.TRIP, ScenicBusinessTypes.MULTI_TRIP].includes(
											item.business_type
										)
									"
								/>
								<detail-tickets
									v-for="(ticketItem, index) in item.items"
									:data="ticketItem"
									:key="index"
									v-else
									@handleBooking="handleBooking"
									@changeBookingTipsShow="changeBookingTipsShow"
								/>
							</view>
						</view>
					</view>
				</template>
				<view v-else class="pb-50">
					<zjy-empty emptyText="当日暂无可预订产品" pdTop="50"></zjy-empty>
				</view>
			</view>
		</view>

		<!-- 景区介绍  -->
		<view id="introduce" class="detail-base-card bg-white introduce" v-if="scenicData.description">
			<view class="title">
				<view class="title-left">景区介绍</view>
				<view class="title-right"></view>
			</view>
			<detail-description
				:description="scenicData.description"
				:id="scenicData.id"
				@richTextReady="richTextReady"
			/>
		</view>
		<!--点评笔记-->
		<view id="notes" class="notes">
			<view class="detail-base-card column-card" v-if="scenicData.articles.length">
				<view class="title">
					<view class="title-left">达人笔记</view>
					<view class="title-right">
						<view class="text">看看别人怎么玩</view>
						<image :src="imgBaseUrl + 'icon-right.png'" class="icon-16"></image>
					</view>
				</view>
				<view class="column-content">
					<view class="type-article" v-for="(article, index) in scenicData.articles" :key="index">
						<view :style="{ 'background-image': 'url(' + article.cover_url + ')' }" class="article-img" />
						<view class="article-content">
							<view class="article-title text-2-ellipsis">{{ article.title }}</view>
							<view class="article-bottom flex-a space-between">
								<view class="flex-a">
									<image :src="article.author_avatar" class="icon-32 circle" />
									<view class="text-ellipsis fs-22 ml-8" style="max-width: 176rpx">
										{{ article.author_name }}
									</view>
								</view>
								<view class="flex-a">
									<image
										class="icon-like"
										:src="imgBaseUrl + (article.like ? 'icon-like-fill.png' : 'icon-like.png')"
									/>
									<view class="fs-24 ml-8">{{ article.like_count }}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="view-all-block">
					<view class="view-all flex-c">
						<text>全部{{ scenicData.article_count }}条笔记</text>
						<image :src="imgBaseUrl + 'icon-right.png'" class="icon-16 ml-8"></image>
					</view>
				</view>
			</view>
			<!--用户点评-->
			<view class="detail-base-card bg-white">
				<view class="title">
					<view class="title-left">用户点评</view>
					<view class="title-right">
						<view class="text">全部123条评论</view>
						<image :src="imgBaseUrl + 'icon-right.png'" class="icon-16"></image>
					</view>
				</view>
				<detail-comment></detail-comment>
				<view class="flex-c">
					<view class="view-all flex-c">
						<text>全部{{ scenicData.article_count }}条评论</text>
						<image :src="imgBaseUrl + 'icon-right.png'" class="icon-16 ml-8"></image>
					</view>
				</view>
			</view>

			<!--价格说明-->
			<view class="detail-base-card bg-white price-instructions">
				<view class="title">
					<view class="title-left">价格说明</view>
				</view>
				<view class="price-desc-text">
					<view class="flex">
						<text>1.</text>
						<text class="ml-4">
							划线价格指商品或服务的门市价、服务提供商的指导价、零售价或该商品或服务曾经展示过的销售价等，并非原价;产品信息实时更新、市场价格波动等原因都可能导致价格与您预订时展示的价格不一致，该价格仅供您参考。
						</text>
					</view>
					<view class="flex">
						<text>2.</text>
						<text class="ml-4">
							未划线价格指商品或服务的实时标价，为在划线价基础上计算的优惠金额。具体成交价格根据商品或服务参与的活动，或会员使用优惠券等具体情况发生变动，最终以订单结算价格为准。
							此说明仅当出现价格比较时有效。若服务提供商单独对划线价格进行说明的，以服务提供商的说明为准。如有疑问，您可以在预订前联系客服进行咨询。
						</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 期望购票日期选择弹窗 -->
		<calendar-popup v-model:model-value="dateCalendarShow" @confirm="handleDateCalendarConfirm" />
		<!-- 公告 -->
		<notice-popup
			v-if="scenicData.notice"
			v-model="noticePopupShow"
			:title="scenicData.notice.title"
			:content="scenicData.notice.content"
			@handleShowNotice="handleShowNotice"
		/>
		<booking-tips
			v-model="bookingTipsShow"
			:data="tipData"
			v-if="tipData"
			@changeBookingTipsShow="changeBookingTipsShow"
			@handleBooking="handleBooking"
		/>
	</view>
</template>

<script setup lang="ts">
import { onLoad, onPageScroll } from "@dcloudio/uni-app"
import dayjs from "dayjs"
import { throttle } from "lodash"
import CalendarPopup from "@/pages/hy/scenic/components/calendar-popup/calendar-popup.vue"
import ZjyStickyTab from "@/components/zjy-sticky-tab.vue"
import DetailInfo from "@/pages/hy/scenic/components/detail-info.vue"
import DetailTourTickets from "@/pages/hy/scenic/components/detail-tour-tickets.vue"
import DetailTickets from "@/pages/hy/scenic/components/detail-tickets.vue"
import DetailBanner from "@/pages/hy/scenic/components/detail-banner.vue"
import NoticePopup from "@/pages/hy/scenic/components/notice-popup.vue"
import BookingTips from "@/pages/hy/scenic/components/booking-tips.vue"
import DetailComment from "@/pages/hy/scenic/components/detail-comment.vue"
import DetailDescription from "@/pages/hy/scenic/components/detail-description.vue"
import useCommonStore from "@/store/common"
import immersiveNavbar from "@/mixins/immersive-navbar"
import { pageBack, pageToTicketBooking, pageToCombotktBooking, pageToTripDetail } from "@/utils/page-redirect"
import { $getScenicDetail, $getScenicProductList } from "@/api/hy/scenic"
import { ScenicBusinessTypes } from "@/constants/common"
import { needLogin } from "@/utils/users"
import { getIdBYScene } from "@/utils/tools"
import { useScrollNavigation } from "@/pages/hy/scenic/hooks/useScrollNavigation"
import { useDateSelector } from "@/pages/hy/scenic/hooks/useDateSelector"
const { statusBarHeight, navbarHeight } = useCommonStore()
const imgBaseUrl = inject("imgBaseUrl")
const id = ref("")
const scenicData = ref<any>(null)
const waitTimeout = ref(true)

const isShowPopup = computed(() => {
	return (
		noticePopupShow.value ||
		dateCalendarShow.value ||
		bookingTipsShow.value ||
		phonePopupShow.value ||
		waitTimeout.value
	)
})
// 倒计时不让页面滚动
setTimeout(() => {
	waitTimeout.value = false
}, 2000)
const tabs = [
	{ id: "ticket-business", name: "预定产品" },
	{ id: "introduce", name: "景区介绍" },
	{ id: "notes", name: "点评笔记" },
]

// 日期选择弹窗
const dateCalendarShow = ref(false)
const openDateCalendar = () => {
	dateCalendarShow.value = true
}
const handleDateCalendarConfirm = (date: string) => {
	selectDateType("custom", date)
	dateCalendarShow.value = false
}
const { isSelected, selectDateType, selectedDate } = useDateSelector()
const instance = getCurrentInstance()?.proxy
watch(selectedDate, async () => {
	await getScenicProductListData()
	currentIndex.value = 0
	uni.pageScrollTo({
		scrollTop: 0,
		duration: 0,
	})
})
// 点击处理函数
const handleClick = (name: string) => {
	uni.showToast({
		title: `点击了${name}`,
		icon: "none",
	})
}
// 预订须知
const bookingTipsShow = ref(false)
const tipData = ref<any>()
const changeBookingTipsShow = ({ show, data }) => {
	bookingTipsShow.value = show
	tipData.value = data
}
// 点击景区评分和点评
const handleCommentClick = () => {
	handleClick("评分点评区域")
}

// 点击公告
const noticePopupShow = ref(false)
const handleShowNotice = (val) => {
	noticePopupShow.value = val
}
// 点击电话
const phonePopupShow = ref(false)
const handleShowPhone = (val) => {
	phonePopupShow.value = val
}

// 点击预定按钮
const handleBooking = (item: any) => {
	if (
		[ScenicBusinessTypes.TICKET, ScenicBusinessTypes.COMBO, ScenicBusinessTypes.PLAY].includes(+item.business_type)
	) {
		// 门票
		pageToTicketBooking({ id: item.id, date: selectedDate.value })
	} else if ([ScenicBusinessTypes.COMBO_TKT].includes(+item.business_type)) {
		// 联票
		pageToCombotktBooking({ id: item.id, date: new Array(item.combos.length).fill(selectedDate.value).join(",") })
	} else if ([ScenicBusinessTypes.TRIP, ScenicBusinessTypes.MULTI_TRIP].includes(+item.business_type)) {
		// 线路
		pageToTripDetail(item.id, { date: selectedDate.value })
	} else {
		uni.showToast({
			title: "暂不支持该预定类型" + item.business_type,
			icon: "none",
		})
	}
}

// 分类数据
const businessTypes = ref([])
const productList = ref([])

// 更新活动索引
const onTabRef = ref(null)
const OFFSET = statusBarHeight + navbarHeight * 2 + 80
const { currentIndex, isClickScroll, updateActiveIndex, getElementPositions, handleCategoryClick } =
	useScrollNavigation(businessTypes, OFFSET)

const getScenicProductListData = async () => {
	$getScenicProductList(id.value, { tour_date: selectedDate.value }).then((res: any) => {
		productList.value = res.list
		businessTypes.value = res.list.map((item: any) => item.business_type_name)

		nextTick(() => {
			getElementPositions()
			// richTextReady()
		})
	})
}
// 富文本渲染完成
const richTextReady = () => {
	waitTimeout.value = false
	if (onTabRef.value) onTabRef.value.calculateTabPositions()
}

onLoad(async (option: any) => {
	id.value = option.id
	if (option.scene) {
		let scene = decodeURIComponent(option.scene)
		id.value = getIdBYScene(scene)
	}

	needLogin()

	scenicData.value = await $getScenicDetail(id.value)
	if (scenicData.value.phones) {
		scenicData.value["phone_list"] = scenicData.value.phones.map((item: any) => {
			return {
				name: item,
			}
		})
	}

	await getScenicProductListData()
})

let { navbarcfg, pageTitle, pageScroll } = immersiveNavbar()
const isReached = ref(false)
const scrollTopVal = ref(0)
// 滚动位置
onPageScroll(
	throttle((e: any) => {
		scrollTopVal.value = e.scrollTop
		pageScroll(scrollTopVal.value)
		pageTitle.value = scenicData.value.name
		if (navbarcfg.value.show) {
			isReached.value = true
		} else {
			isReached.value = false
		}
		if (!isClickScroll.value) {
			updateActiveIndex(scrollTopVal.value)
		}
	}, 300)
)
</script>

<style scoped lang="scss">
.page-container {
	.order-product {
		width: 100%;
		position: relative;
		margin-top: -32rpx;
		z-index: 2;
		border-radius: 16rpx;
		margin-bottom: 16rpx;

		.ticket-business {
			background-color: #fff;
			position: relative;
			.optional-date {
				position: sticky;
				width: 100%;
				z-index: 13;
				padding: 28rpx 24rpx;
				gap: 16rpx;
				display: flex;
				align-items: center;
				overflow-x: scroll;
				background-color: #fff;

				.date {
					flex: 0 0 auto;
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 10rpx 16rpx;
					background: #f7f8f9;
					position: relative;
					border-radius: 8rpx;
					border: 1rpx solid transparent;

					.icon-filter {
						width: 20rpx;
						height: 16rpx;
						display: none;
						position: absolute;
						right: -1rpx;
						bottom: -1rpx;
					}

					&.selected {
						background: rgba(254, 224, 56, 0.2);
						border: 1rpx solid #fee038;

						.icon-filter {
							display: block;
						}
					}
				}
			}

			.ticket {
				display: flex;
				height: max-content;
				background-color: $grey;

				.ticket-category {
					height: max-content;
					position: sticky;
					width: 144rpx;
					z-index: 12;

					.category {
						width: 144rpx;
						height: 100rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 24rpx;
						color: #333;
						position: relative;

						&.active {
							color: #1d2129;
							background: #fff;
							font-weight: 500;
						}
					}
				}

				.ticket-list {
					background-color: #f7f8f9;
					height: auto;
					width: calc(100% - 144rpx);
					overflow-x: hidden;

					.ticket-item {
						margin-top: 16rpx;

						.title {
							font-size: 24rpx;
							font-weight: 500;
							margin-bottom: 16rpx;
							padding-left: 24rpx;
						}

						.tickets {
							background-color: #fff;
							padding-bottom: 24rpx;
						}

						&:last-child {
							margin-bottom: 0;
						}
					}
				}
			}
		}
	}

	.detail-base-card {
		position: relative;
		width: 100%;
		padding: 32rpx 24rpx;
		margin-bottom: 16rpx;
		border-radius: 16rpx;

		.title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 24rpx;

			.title-left {
				display: flex;
				align-items: center;
				font-size: 36rpx;
				color: #000;
				font-weight: 600;
			}

			.title-right {
				height: 100%;
				display: flex;
				align-items: flex-end;

				.text {
					font-size: 24rpx;
					font-weight: normal;
					color: #787a7f;
				}

				image {
					margin-left: 4rpx;
					transform: translateY(-8rpx);
				}
			}
		}
		.view-all-block {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			height: 120rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-image: linear-gradient(-180deg, rgba(255, 255, 255, 0) 0%, #fff 80%);
		}

		.view-all {
			width: 240rpx;
			height: 64rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border: 1px solid #e5e6eb;
			border-radius: 32rpx;
			background-color: rgba(255, 255, 255, 0.6);
		}
	}
	.price-desc-text {
		line-height: 48rpx;
		color: $c-grey-4e;
	}
}

.column-card {
	background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0) 100%);

	.column-content {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 18rpx;
		position: relative;
	}
}
.type-article {
	border-radius: 16rpx;
	overflow: hidden;
	position: relative;
	.article-img {
		border-top-left-radius: 16rpx;
		border-top-right-radius: 16rpx;
		width: 100%;
		height: 456rpx;
		background-position: center center;
		background-size: cover;
	}
	.article-content {
		background: $c-white;
		padding: 16rpx 20rpx;
		border-bottom-left-radius: 16rpx;
		border-bottom-right-radius: 16rpx;

		.article-title {
			font-size: 28rpx;
			color: $c-black-1d;
		}
		.article-bottom {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-top: 20rpx;
			font-size: 22rpx;
			color: $c-grey-86;
			.icon-like {
				width: 26rpx;
				height: 24rpx;
			}
		}
	}
}
</style>
